package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    private static final  long BEGIN_TIMESTAMP = 1640995299L;
    private static final  long COUNT_BITS = 32;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix){
        //1、生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //当前秒的时间戳 - 20220101的时间秒的时间戳 ，这样用户就看不出时间的规律
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;  //当前时间-20220101的时间秒的时间戳

        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        //位运算之后做个假发
        return timeStamp << COUNT_BITS | count;
    }
}
